<script lang="ts" setup>
import { ref, nextTick } from 'vue'
import wjzs from '@/components/wjzs.vue'
import { useMainStore } from '@/store/main'
import gdglService from '@/api/gdgl'
import { ElMessage } from 'element-plus'
import printFn from '@/utils/print'
// 入参
const store = useMainStore()
// ref
const wjzsRef = ref()
/*
 * 打开弹框
 */

const dialogVisible = ref(false)
const paramsData = ref()
const openDialog = (data: any) => {
  paramsData.value = data
  dialogVisible.value = true
  getUrlTgspb()
}

const urlDialog = ref()

const getUrlTgspb = () => {
  const params = {
    gdjlbh: paramsData.value.gdjlbh,
    jlbh: paramsData.value.jlbh || paramsData.value.tgjlbh,
    dwmc: store.userInfo.dwmc,
  }
  gdglService
    .getTgspb(params)
    .then((res) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        urlDialog.value = window.URL.createObjectURL(res.data)
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}
// 下载按钮
const download = () => {
  const downloadElement = document.createElement('a')
  downloadElement.href = urlDialog.value
  downloadElement.download = '退改审批表.pdf'
  document.body.appendChild(downloadElement)
  downloadElement.click() //点击下载
  document.body.removeChild(downloadElement) //下载完成移除元素
}

const print = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '归档审批表.pdf',
    loadingHeader: {},
    loadingParam: {
      gdjlbh: paramsData.value.gdjlbh,
      jlbh: paramsData.value.jlbh || paramsData.value.tgjlbh,
      dwmc: store.userInfo.dwmc,
    },
    loadingUrl: `${window.IPCONFIG}/api/gdgl/getTgspb`,
    requestMethodName: 'GET',
  }
  printFn(params)
}
defineExpose({ openDialog })
</script>
<template>
  <el-dialog v-model="dialogVisible" title="退改审批表" width="80%" :close-on-click-modal="false">
    <div class="dialog-box">
      <!--文件-->
      <wjzs ref="wjzsRef" wjlx="pdf" :url="urlDialog" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="download">下载</el-button>
        <el-button type="primary" @click="print">打印</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  height: 70vh;
}
</style>
